package com.hbnu.sunjianwei.questionbank;

import com.hbnu.sunjianwei.questionbank.dao.QuestionDao;
import com.hbnu.sunjianwei.questionbank.entity.ExamPaper;
import com.hbnu.sunjianwei.questionbank.entity.Question;
import com.hbnu.sunjianwei.questionbank.util.TextExportUtil;
import com.hbnu.sunjianwei.questionbank.util.WordExportUtil;

import java.util.List;
import java.util.Scanner;

public class Main {
    private static QuestionDao questionDao = new QuestionDao();
    private static Scanner scanner = new Scanner(System.in);
    private static int totalQuestionsAnswered = 0;
    private static int correctAnswers = 0;


    public static void main(String[] args) {
        System.out.println("=== 智能题库系统 ===");

        // 测试数据库连接
        if (!questionDao.testConnection()) {
            System.err.println("❌ 数据库连接失败，请检查配置！");
            return;
        }
        System.out.println("✅ 数据库连接成功");

        // 显示主菜单
        showMainMenu();
    }

    private static void showMainMenu() {
        QuestionDao dao = new QuestionDao();

        while (true) {
            System.out.println("\n=== 智能题库系统 ===");
            System.out.println("1. 查看所有题目");
            System.out.println("2. 查看题目详情");
            System.out.println("3. 题目统计");
            System.out.println("4. 添加题目");
            System.out.println("5. 随机抽题");
            System.out.println("6. 自动组卷");
            System.out.println("7. 答题统计");
            System.out.println("8. 退出系统");
            System.out.print("请选择操作: ");

            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    showAllQuestions();
                    break;
                case "2":
                    showQuestionDetail();
                    break;
                case "3":
                    dao.showQuestionStats();
                    System.out.println("总题目数: " + dao.getQuestionCount());
                    break;
                case "4":
                    addQuestion();
                    break;
                case "5":
                    showRandomQuestionMenu();
                    break;
                case "6":
                    showExamGenerationMenu();
                    break;
                case "7":
                    showAnswerStats();
                    break;
                case "8":
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入");
            }
        }
    }

    private static void showAllQuestions() {
        System.out.println("\n=== 所有题目 ===");
        List<Question> questions = questionDao.getAllQuestions();

        if (questions.isEmpty()) {
            System.out.println("题库为空");
            return;
        }

        for (Question question : questions) {
            System.out.println(question);
        }
        System.out.println("共 " + questions.size() + " 道题目");
    }

    private static void showQuestionDetail() {
        System.out.print("\n请输入题目ID: ");
        try {
            int id = Integer.parseInt(scanner.nextLine());
            Question question = questionDao.getQuestionById(id);

            if (question == null) {
                System.out.println("❌ 未找到该题目");
                return;
            }

            System.out.println("\n=== 题目详情 ===");
            System.out.println("ID: " + question.getId());
            System.out.println("题目: " + question.getQuestionText());
            System.out.println("类型: " + getQuestionTypeName(question.getQuestionType()));
            System.out.println("难度: " + getDifficultyName(question.getDifficulty()));
            System.out.println("科目: " + question.getSubject());

            // 根据题目类型显示不同内容
            if ("TRUE_FALSE".equals(question.getQuestionType())) {
                System.out.println("判断题选项: A.正确  B.错误");
            } else {
                // 选择题显示具体选项
                displayOptions(question);
            }

            System.out.println("正确答案: " + formatCorrectAnswer(question));

        } catch (NumberFormatException e) {
            System.out.println("❌ 请输入有效的数字ID");
        }
    }

    /**
     * 显示选择题选项
     */
    private static void displayOptions(Question question) {
        if (question.getOptionA() != null && !question.getOptionA().trim().isEmpty())
            System.out.println("A. " + question.getOptionA());
        if (question.getOptionB() != null && !question.getOptionB().trim().isEmpty())
            System.out.println("B. " + question.getOptionB());
        if (question.getOptionC() != null && !question.getOptionC().trim().isEmpty())
            System.out.println("C. " + question.getOptionC());
        if (question.getOptionD() != null && !question.getOptionD().trim().isEmpty())
            System.out.println("D. " + question.getOptionD());
    }

    /**
     * 获取题目类型的中文名称
     */
    private static String getQuestionTypeName(String type) {
        switch (type) {
            case "SINGLE": return "单选题";
            case "MULTIPLE": return "多选题";
            case "TRUE_FALSE": return "判断题";
            default: return type;
        }
    }

    /**
     * 获取难度的中文名称
     */
    private static String getDifficultyName(String difficulty) {
        switch (difficulty) {
            case "EASY": return "简单";
            case "MEDIUM": return "中等";
            case "HARD": return "困难";
            default: return difficulty;
        }
    }

    /**
     * 格式化正确答案显示
     */
    private static String formatCorrectAnswer(Question question) {
        String answer = question.getCorrectAnswer();
        if ("TRUE_FALSE".equals(question.getQuestionType())) {
            return "A".equals(answer) ? "正确" : "错误";
        }
        return answer;
    }

    private static void addQuestion() {
        while (true) {
            System.out.println("\n=== 添加新题目 ===");

            Question question = new Question();

            // 输入题目内容
            System.out.print("请输入题目内容: ");
            String questionText = scanner.nextLine();
            if (questionText.trim().isEmpty()) {
                System.out.println("题目内容不能为空！");
                continue;
            }
            question.setQuestionText(questionText);

            // 选择题目类型
            question.setQuestionType(selectQuestionType());

            // 根据题目类型输入选项
            if (!"TRUE_FALSE".equals(question.getQuestionType())) {
                System.out.print("请输入选项A: ");
                question.setOptionA(scanner.nextLine());
                System.out.print("请输入选项B: ");
                question.setOptionB(scanner.nextLine());
                System.out.print("请输入选项C: ");
                question.setOptionC(scanner.nextLine());
                System.out.print("请输入选项D: ");
                question.setOptionD(scanner.nextLine());
            }

            // 输入正确答案
            question.setCorrectAnswer(selectCorrectAnswer(question.getQuestionType()));

            // 选择难度
            question.setDifficulty(selectDifficulty());

            // 输入科目
            System.out.print("请输入科目: ");
            String subject = scanner.nextLine();
            if (subject.trim().isEmpty()) {
                subject = "未分类";
            }
            question.setSubject(subject);

            // 预览题目
            System.out.println("\n=== 题目预览 ===");
            displayQuestionPreview(question);

            // 确认添加
            System.out.print("\n确认添加这个题目吗？(y/N): ");
            String confirm = scanner.nextLine();

            if ("y".equalsIgnoreCase(confirm)) {
                QuestionDao dao = new QuestionDao();
                if (dao.addQuestion(question)) {
                    System.out.println("✅ 题目添加成功！");
                } else {
                    System.out.println("❌ 题目添加失败！");
                }
            } else {
                System.out.println("取消添加题目");
            }

            // 询问是否继续添加
            System.out.print("\n是否继续添加题目？(y/N): ");
            String continueAdd = scanner.nextLine();
            if (!"y".equalsIgnoreCase(continueAdd)) {
                break;
            }
        }
    }

    private static String selectQuestionType() {
        while (true) {
            System.out.println("请选择题型:");
            System.out.println("1. 单选题");
            System.out.println("2. 判断题");
            System.out.print("请选择(1-2): ");

            String choice = scanner.nextLine();
            switch (choice) {
                case "1": return "SINGLE";
                case "2": return "TRUE_FALSE";
                default: System.out.println("无效选择，请重新输入");
            }
        }
    }

    private static String selectCorrectAnswer(String questionType) {
        if ("TRUE_FALSE".equals(questionType)) {
            while (true) {
                System.out.println("请选择正确答案:");
                System.out.println("1. 正确");
                System.out.println("2. 错误");
                System.out.print("请选择(1-2): ");

                String choice = scanner.nextLine();
                switch (choice) {
                    case "1": return "A";
                    case "2": return "B";
                    default: System.out.println("无效选择，请重新输入");
                }
            }
        } else {
            while (true) {
                System.out.print("请输入正确答案(A/B/C/D): ");
                String answer = scanner.nextLine().toUpperCase();
                if (answer.matches("[A-D]")) {
                    return answer;
                }
                System.out.println("无效答案，请输入A、B、C或D");
            }
        }
    }

    private static String selectDifficulty() {
        while (true) {
            System.out.println("请选择难度:");
            System.out.println("1. 简单");
            System.out.println("2. 中等");
            System.out.println("3. 困难");
            System.out.print("请选择(1-3): ");

            String choice = scanner.nextLine();
            switch (choice) {
                case "1": return "EASY";
                case "2": return "MEDIUM";
                case "3": return "HARD";
                default: System.out.println("无效选择，请重新输入");
            }
        }
    }

    private static void displayQuestionPreview(Question question) {
        System.out.println("题目: " + question.getQuestionText());
        System.out.println("类型: " + getQuestionTypeName(question.getQuestionType()));
        System.out.println("难度: " + getDifficultyName(question.getDifficulty()));
        System.out.println("科目: " + question.getSubject());

        if ("TRUE_FALSE".equals(question.getQuestionType())) {
            System.out.println("判断题选项: A.正确  B.错误");
        } else {
            if (question.getOptionA() != null && !question.getOptionA().isEmpty())
                System.out.println("A. " + question.getOptionA());
            if (question.getOptionB() != null && !question.getOptionB().isEmpty())
                System.out.println("B. " + question.getOptionB());
            if (question.getOptionC() != null && !question.getOptionC().isEmpty())
                System.out.println("C. " + question.getOptionC());
            if (question.getOptionD() != null && !question.getOptionD().isEmpty())
                System.out.println("D. " + question.getOptionD());
        }

        System.out.println("正确答案: " + formatCorrectAnswer(question));
    }

    private static void showRandomQuestionMenu() {
        while (true) {
            System.out.println("\n=== 随机抽题 ===");
            System.out.println("1. 随机抽一题");
            System.out.println("2. 按科目抽题");
            System.out.println("3. 返回主菜单");
            System.out.print("请选择操作: ");

            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    takeRandomQuestion();
                    break;
                case "2":
                    takeRandomQuestionBySubject();
                    break;
                case "3":
                    return;
                default:
                    System.out.println("无效选择，请重新输入");
            }
        }
    }
    private static void takeRandomQuestion() {
        System.out.println("\n=== 随机抽题 ===");

        QuestionDao dao = new QuestionDao();
        Question question = dao.getRandomQuestion();

        if (question == null) {
            System.out.println("❌ 题库为空，无法抽题");
            return;
        }

        // 显示题目并获取用户答案
        boolean isCorrect = displayQuestionAndGetAnswer(question);

        // 显示结果
        if (isCorrect) {
            System.out.println("🎉 回答正确！");
        } else {
            System.out.println("❌ 回答错误！");
            System.out.println("正确答案: " + formatCorrectAnswer(question));
        }
    }

    private static void takeRandomQuestionBySubject() {
        System.out.println("\n=== 按科目抽题 ===");

        QuestionDao dao = new QuestionDao();
        List<String> subjects = dao.getAllSubjects();

        if (subjects.isEmpty()) {
            System.out.println("❌ 没有可用的科目");
            return;
        }

        // 显示科目列表
        System.out.println("请选择科目:");
        for (int i = 0; i < subjects.size(); i++) {
            System.out.println((i + 1) + ". " + subjects.get(i));
        }

        System.out.print("请选择科目(1-" + subjects.size() + "): ");
        try {
            int choice = Integer.parseInt(scanner.nextLine());
            if (choice < 1 || choice > subjects.size()) {
                System.out.println("❌ 无效选择");
                return;
            }

            String selectedSubject = subjects.get(choice - 1);
            Question question = dao.getRandomQuestionBySubject(selectedSubject);

            if (question == null) {
                System.out.println("❌ 该科目下没有题目");
                return;
            }

            // 显示题目并获取用户答案
            boolean isCorrect = displayQuestionAndGetAnswer(question);

            // 显示结果
            if (isCorrect) {
                System.out.println("🎉 回答正确！");
            } else {
                System.out.println("❌ 回答错误！");
                System.out.println("正确答案: " + formatCorrectAnswer(question));
            }

        } catch (NumberFormatException e) {
            System.out.println("❌ 请输入有效的数字");
        }
    }

    private static boolean displayQuestionAndGetAnswer(Question question) {
        System.out.println("\n=== 题目 ===");
        System.out.println("科目: " + question.getSubject());
        System.out.println("难度: " + getDifficultyName(question.getDifficulty()));
        System.out.println("题目: " + question.getQuestionText());

        // 显示选项
        if ("TRUE_FALSE".equals(question.getQuestionType())) {
            System.out.println("A. 正确");
            System.out.println("B. 错误");
        } else {
            if (question.getOptionA() != null && !question.getOptionA().isEmpty())
                System.out.println("A. " + question.getOptionA());
            if (question.getOptionB() != null && !question.getOptionB().isEmpty())
                System.out.println("B. " + question.getOptionB());
            if (question.getOptionC() != null && !question.getOptionC().isEmpty())
                System.out.println("C. " + question.getOptionC());
            if (question.getOptionD() != null && !question.getOptionD().isEmpty())
                System.out.println("D. " + question.getOptionD());
        }

        // 获取用户答案
        String userAnswer;
        while (true) {
            System.out.print("请输入你的答案(A/B/C/D): ");
            userAnswer = scanner.nextLine().toUpperCase();

            if (userAnswer.matches("[A-D]")) {
                break;
            }
            System.out.println("❌ 无效答案，请输入A、B、C或D");
        }

        // 更新统计
        totalQuestionsAnswered++;
        boolean isCorrect = userAnswer.equals(question.getCorrectAnswer());
        if (isCorrect) {
            correctAnswers++;
        }

        return isCorrect;
    }

    // 添加统计显示方法
    private static void showAnswerStats() {
        if (totalQuestionsAnswered == 0) {
            System.out.println("还没有答题记录");
            return;
        }

        double accuracy = (double) correctAnswers / totalQuestionsAnswered * 100;
        System.out.println("\n=== 答题统计 ===");
        System.out.println("答题总数: " + totalQuestionsAnswered);
        System.out.println("正确数: " + correctAnswers);
        System.out.println("正确率: " + String.format("%.2f", accuracy) + "%");
    }
    private static void showExamGenerationMenu() {
        while (true) {
            System.out.println("\n=== 自动组卷 ===");
            System.out.println("1. 随机组卷");
            System.out.println("由于示例题库题目数量较少、科目较杂目前仅支持随机组卷，");
            System.out.println("未来可能实现按科目组卷和按难度组卷");
            System.out.println("4. 返回主菜单");
            System.out.print("请选择: ");

            String choice = scanner.nextLine();

            switch (choice) {
                case "1":
                    generateRandomExam();
                    break;
                case "4":
                    return;
                default:
                    System.out.println("无效选择，请重新输入");
            }
        }
    }
    private static void generateRandomExam() {
        System.out.println("\n=== 随机组卷 ===");

        // 获取题目数量
        int questionCount = getQuestionCount();
        if (questionCount == 0) return;

        // 获取试卷标题
        System.out.print("请输入试卷标题: ");
        String title = scanner.nextLine();
        if (title.trim().isEmpty()) {
            title = "随机试卷";
        }

        // 生成试卷
        QuestionDao dao = new QuestionDao();
        List<Question> questions = dao.getRandomQuestions(questionCount);

        if (questions.isEmpty()) {
            System.out.println("❌ 无法生成试卷，题库可能为空");
            return;
        }

        // 创建试卷对象
        ExamPaper examPaper = new ExamPaper();
        examPaper.setTitle(title);
        examPaper.setQuestions(questions);
        examPaper.setCreateTime(java.time.LocalDateTime.now().toString());

        // 预览试卷
        previewExamPaper(examPaper);

        // 导出试卷
        exportExamPaper(examPaper);
    }

    private static int getQuestionCount() {
        while (true) {
            System.out.print("请输入题目数量: ");
            try {
                int count = Integer.parseInt(scanner.nextLine());
                if (count <= 0) {
                    System.out.println("❌ 题目数量必须大于0");
                    continue;
                }

                QuestionDao dao = new QuestionDao();
                int totalQuestions = dao.getQuestionCount();

                if (count > totalQuestions) {
                    System.out.println("❌ 题目数量不能超过题库总数(" + totalQuestions + ")");
                    continue;
                }

                return count;
            } catch (NumberFormatException e) {
                System.out.println("❌ 请输入有效的数字");
            }
        }
    }

    private static void previewExamPaper(ExamPaper examPaper) {
        System.out.println("\n=== 试卷预览 ===");
        System.out.println("试卷标题: " + examPaper.getTitle());
        System.out.println("题目数量: " + examPaper.getQuestions().size());
        System.out.println("生成时间: " + examPaper.getCreateTime());
        System.out.println();

        List<Question> questions = examPaper.getQuestions();
        for (int i = 0; i < questions.size(); i++) {
            Question q = questions.get(i);
            System.out.println((i + 1) + ". " + q.getQuestionText());
            System.out.println("   科目: " + q.getSubject() + " | 难度: " + getDifficultyName(q.getDifficulty()));
            System.out.println();
        }

        System.out.print("是否导出这份试卷？(y/N): ");
        String confirm = scanner.nextLine();
        if (!"y".equalsIgnoreCase(confirm)) {
            System.out.println("取消导出");
            return;
        }
    }

    private static void exportExamPaper(ExamPaper examPaper) {
        // 设置导出路径
        String exportPath = "./exports/";

        // 生成文件名
        String examFileName = WordExportUtil.generateFileName(examPaper.getTitle());
        String answerFileName = WordExportUtil.generateFileName(examPaper.getTitle() + "_答案");

        // 导出试卷Word文档
        String examFilePath = exportPath + examFileName;
        boolean examSuccess = WordExportUtil.exportExamToWord(examPaper, examFilePath);

        // 导出答案Word文档
        String answerFilePath = exportPath + answerFileName;
        boolean answerSuccess = WordExportUtil.exportAnswersToWord(examPaper, answerFilePath);

        if (examSuccess && answerSuccess) {
            System.out.println("🎉 试卷和答案Word文档导出成功！");
            System.out.println("试卷文件: " + examFileName);
            System.out.println("答案文件: " + answerFileName);
        } else {
            System.out.println("❌ Word文档导出失败，请检查目录权限");

            // 如果Word导出失败，回退到文本导出
            System.out.println("尝试使用文本格式导出...");
            fallbackToTextExport(examPaper);
        }
    }

    /**
     * 回退到文本导出（备用方案）
     */
    private static void fallbackToTextExport(ExamPaper examPaper) {
        String exportPath = "./exports/";

        // 生成文件名
        String examFileName = TextExportUtil.generateFileName(examPaper.getTitle());
        String answerFileName = TextExportUtil.generateFileName(examPaper.getTitle() + "_答案");

        // 导出试卷文本文件
        String examFilePath = exportPath + examFileName;
        boolean examSuccess = TextExportUtil.exportExamPaper(examPaper, examFilePath);

        // 导出答案文本文件
        String answerFilePath = exportPath + answerFileName;
        boolean answerSuccess = TextExportUtil.exportAnswerSheet(examPaper, answerFilePath);

        if (examSuccess && answerSuccess) {
            System.out.println("✅ 试卷和答案文本文件导出成功！");
            System.out.println("试卷文件: " + examFileName);
            System.out.println("答案文件: " + answerFileName);
        } else {
            System.out.println("❌ 所有导出方式均失败");
        }
    }
}